package com.dz.lm.common.util;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.smartlbs.util.UploadFile;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.common.utils.random.RandomUtils;

public class FileUploadUtil {

	private static final Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);
	private static InputStream in;
	private static Properties p;
	private static String dev_path = "";
	private static String test_path = "";
	private static String prod_path = "";
	private static String test_Ip = "";
	private static String realm_name = "www.sankedouzi.com";
	private static String realm_name_cn = "www.sankedouzi.cn";
	private static String separator = "/";
	static {
		try {
			in = FileUploadUtil.class.getClassLoader().getResourceAsStream("upload.properties");
			p = new Properties();
			p.load(in);
			dev_path = p.getProperty("dev_upload_path");
			test_path = p.getProperty("test_upload_path");
			prod_path = p.getProperty("prod_upload_path");
			test_Ip = p.getProperty("test_Ip");
		} catch (FileNotFoundException e) {
			logger.error("upload Not Found File :upload.properties");
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("upload IOException");
			e.printStackTrace();
		}
	}
	
	public static List<String> upload(HttpServletRequest request) {
		Object imgUrl = request.getAttribute("imgUrl");
		List<String> retList = new ArrayList<String>();
		String path = "";
		if (imgUrl != null && imgUrl.toString().indexOf(test_Ip) > 0  || imgUrl.toString().indexOf(realm_name) > 0 || imgUrl.toString().indexOf(realm_name_cn) > 0) {
			if (test_path == null || "".equals(test_path)) {
				path = prod_path;
			} else {
				path = test_path;
			}
		} else {
			path = dev_path;
		}
		String subPath = separator + DateUtil.dateToYYYYMMDD(new Date()) + separator;
		try {
		    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		    Iterator<String> iter = multiRequest.getFileNames();
			File image = null;
			String fileName = null;
			while (iter.hasNext()) {
			    MultipartFile multipartFile = multiRequest.getFile(iter.next());
			    fileName = multipartFile.getOriginalFilename();
			    fileName = MD5Util.MD5(fileName);
			    image = new File(path + subPath + fileName);
			    multipartFile.transferTo(image);
			    retList.add(subPath + fileName);
		    }
		} catch (Exception e) {
		    e.printStackTrace();
		}
		return retList;
	}
	
	/**
	 * 图片上传至服务器
	 * @param images 图片流集合
	 * @param imgUrl 图片上传服务器地址
	 * @param type 固定值(需求图片：needs;
	 *                    产品图片：product;
	 *                    经理人认证图片：authManager;
	 *                    头像图片：profile;
	 *                    钱吧图片：moneyBar;
	 *                    借贷名片图片：creditCard;
	 *                    小程序二维码：scanCode)
	 * @return 上传成功的图片URL
	 * @author zhang-hr
	 * @since 2019/07/01
	 */
	public static Map<String, Object> uploadByInStream(Map<String, Object> images, Object imgUrl, String type) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		String path = "";
		if (imgUrl != null && (imgUrl.toString().indexOf(test_Ip) > 0 || imgUrl.toString().indexOf(realm_name) > 0 || imgUrl.toString().indexOf(realm_name_cn) > 0)) {
			if (test_path == null || "".equals(test_path)) {
				path = prod_path;
			} else {
				path = test_path;
			}
		} else {
			path = dev_path;
		}
		String subPath = separator + type + separator + DateUtil.dateToYYYYMMDD(new Date()) + separator;
		try {
			Set<String> keys = images.keySet();
			File image = null;
			String fileName = null;
			String suffixName = null;
			FileItem fi = null;
			InputStream in = null;
			FileOutputStream fos = null;
			for (String key : keys) {
				try {
					File validateFolder = new File(path + subPath);
					logger.info("FilePath:" + path + subPath);
					if (!validateFolder.exists()) {
						validateFolder.mkdirs();
						logger.info("Folder create Success!");
					}

					fi = (FileItem) images.get(key);
					fileName = fi.getName();
					if (fileName != null) {
						// 这里加一个限制，如果不是图片格式，则提示错误. (jpg,jpeg,bmp,png,pdf)
	                    suffixName = FilenameUtils.getExtension(fileName);
	                    if ("jpg".equalsIgnoreCase(suffixName)
	                    		|| "jpeg".equalsIgnoreCase(suffixName)
	                            || "bmp".equalsIgnoreCase(suffixName)
	                            || "png".equalsIgnoreCase(suffixName)
	                            || "pdf".equalsIgnoreCase(suffixName)) {
	                    	
	                    } else {
	                    	logger.error("文件格式错误!");
	                    	continue;
	                    }
					}
					fileName = MD5Util.MD5(RandomUtils.generateString(16));
					fileName = fileName + "." + suffixName;
					in = fi.getInputStream();
					image = new File(path + subPath + fileName);// 可以是任何图片格式.jpg,.png等
					fos = new FileOutputStream(image);
					byte[] b = new byte[1024];
					int nRead = 0;
					while ((nRead = in.read(b)) != -1) {
						fos.write(b, 0, nRead);
					}
					fos.flush();
					retMap.put(key, "/img" + subPath + fileName);
					logger.info("Upload Success!");
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					fos.close();
					in.close();
					fi = null;
				}
			}
		} catch (Exception e) {
		    e.printStackTrace();
		}
		return retMap;
	}
	public static Map<String, Object> uploadByInStream(List<UploadFile> fList, Object imgUrl, String type) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		String path = "";
		if (imgUrl != null && (imgUrl.toString().indexOf(test_Ip) > 0 || imgUrl.toString().indexOf(realm_name) > 0 || imgUrl.toString().indexOf(realm_name_cn) > 0)) {
			if (test_path == null || "".equals(test_path)) {
				path = prod_path;
			} else {
				path = test_path;
			}
		} else {
			path = dev_path;
		}
		String subPath = separator + type + separator + DateUtil.dateToYYYYMMDD(new Date()) + separator;
		try {
			File image = null;
			String fileName = null;
			String suffixName = null;
			InputStream in = null;
			FileOutputStream fos = null;
			for (UploadFile file : fList) {
				try {
					File validateFolder = new File(path + subPath);
					logger.info("FilePath:" + path + subPath);
					if (!validateFolder.exists()) {
						validateFolder.mkdirs();
						logger.info("Folder create Success!");
					}

					fileName = file.getFile_name();
					if (fileName != null) {
						// 这里加一个限制，如果不是图片格式，则提示错误. (jpg,jpeg,bmp,png,pdf)
						suffixName = FilenameUtils.getExtension(fileName);
						if ("jpg".equalsIgnoreCase(suffixName)
								|| "jpeg".equalsIgnoreCase(suffixName)
								|| "bmp".equalsIgnoreCase(suffixName)
								|| "png".equalsIgnoreCase(suffixName)
								|| "pdf".equalsIgnoreCase(suffixName)
								|| "DOC".equalsIgnoreCase(suffixName)
								|| "DOC".equalsIgnoreCase(suffixName)
								|| "XLS".equalsIgnoreCase(suffixName)
								|| "XLSX".equalsIgnoreCase(suffixName)

								) {

						} else {
							logger.error("文件格式错误!");
							continue;
						}
					}
					fileName = MD5Util.MD5(RandomUtils.generateString(16));
					fileName = fileName + "." + suffixName;
					in = new ByteArrayInputStream(file.getFile_bytes());
					image = new File(path + subPath + fileName);// 可以是任何图片格式.jpg,.png等
					fos = new FileOutputStream(image);
					byte[] b = new byte[1024];
					int nRead = 0;
					while ((nRead = in.read(b)) != -1) {
						fos.write(b, 0, nRead);
					}
					fos.flush();
					retMap.put(file.getField_name(), "/img" + subPath + fileName);
					logger.info("Upload Success!");
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					fos.close();
					in.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;
	}
	/**
	 * 图片上传至服务器
	 * @param in 图片流集合
	 * @param imgUrl 图片上传服务器地址
	 * @param type 固定值(小程序二维码：scanCode)
	 * @return 上传成功的图片URL
	 * @author zhang-hr
	 * @since 2019/07/01
	 */
	public static Map<String, Object> uploadInStream(InputStream in, Object imgUrl, String type) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		String path = "";
		if (imgUrl != null && (imgUrl.toString().indexOf(test_Ip) > 0 || imgUrl.toString().indexOf(realm_name) > 0 || imgUrl.toString().indexOf(realm_name_cn) > 0)) {
			if (test_path == null || "".equals(test_path)) {
				path = prod_path;
			} else {
				path = test_path;
			}
		} else {
			path = dev_path;
		}
		String subPath = separator + type + separator + DateUtil.dateToYYYYMMDD(new Date()) + separator;
		try {
			File image = null;
			String fileName = null;
			String suffixName = "png";
			FileOutputStream fos = null;
			try {
				File validateFolder = new File(path + subPath);
				logger.info("FilePath:" + path + subPath);
				if (!validateFolder.exists()) {
					validateFolder.mkdirs();
					logger.info("Folder create Success!");
				}
				fileName = MD5Util.MD5(RandomUtils.generateString(16));
				fileName = fileName + "." + suffixName;
				image = new File(path + subPath + fileName);// 可以是任何图片格式.jpg,.png等
				fos = new FileOutputStream(image);
				byte[] b = new byte[1024];
				int nRead = 0;
				while ((nRead = in.read(b)) != -1) {
					fos.write(b, 0, nRead);
				}
				fos.flush();
				retMap.put("scanCode", "/img" + subPath + fileName);
				logger.info("Upload Success!");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				fos.close();
				in.close();
			}
		} catch (Exception e) {
		    e.printStackTrace();
		}
		return retMap;
	}
	
	/**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
		String path = "";
		if (fileName != null && fileName.toString().indexOf(test_Ip) > 0 || fileName.toString().indexOf(realm_name) > 0 || fileName.toString().indexOf(realm_name_cn) > 0) {
			path = test_path;
		} else {
			path = dev_path;
		}
    	if (fileName.indexOf("/img/") > 0) {
    		fileName = path + fileName.substring(fileName.indexOf("/img/") + 4);
    	}
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
            	logger.info("删除文件" + fileName + "成功！");
                return true;
            } else {
            	logger.info("删除文件" + fileName + "失败！");
                return false;
            }
        } else {
        	logger.info("删除文件失败：" + fileName + "不存在！");
            return false;
        }
    }
}
